package org.hbm.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static SessionFactory sf;
	static{
		try {
			/**默认加载src下的配置文件hibernate.cfg.xml，并解析xml映射文件和实体注解映射
			 * 注：new Configuration().configure()只能解析xml映射文件
			 */
			Configuration config=new AnnotationConfiguration().configure();
			sf=config.buildSessionFactory();
		} catch (HibernateException e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}
	public static Session getSession(){
		return sf.openSession();
	}
	public static void closeSessionFactory(){
		if(!sf.isClosed()){
			sf.close();
		}
	}
	public static Session insulateSession(Session session){
		if(!session.isOpen()){
			session.close();
		}
		return getSession();
	}
}
